package jt.classic.app.dms;

import jt.classic.system.ISystem;
import jt.classic.system.LicenseAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.purview.PurviewManager;
import jt.classic.system.user.IUser;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.limp.basework.SimpleBean4Table;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.impl.SimpleBean4TableImpl;
import org.limp.basework.tools.BaseworkUtil;

import org.limp.mine.Controller;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;

import java.sql.Connection;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 文档共享设置控制器
 *
 * @author mido
 *
 */
public class DmsShareAction extends LicenseAction {
    /**
     * 混合共享设置
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward shared4remix(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String params = StringTool.checkString(param.get("params"));

        JSONObject jsonObj = JSONObject.fromObject(params);
        JSONArray array = jsonObj.getJSONArray("result");

        if ((array != null) && (array.size() > 0)) {
            BaseworkUtil util = new BaseworkUtil();

            SimpleBean4Table temp = new SimpleBean4TableImpl("ISYS_PURVIEW");

            try {
                SystemDataSource ds = SystemDataSource.getInstance();
                conn = ds.getConnection();

                PurviewManager manager = new PurviewManager(conn);

                for (int i = 0; i < array.size(); i++) {
                    JSONObject json = array.getJSONObject(i);
                    String rid = json.getString("rid");
                    String rname = json.getString("rname");
                    String rtype = json.getString("rtype");
                    String[] oids = json.getString("oid").split(",");
                    String[] onames = json.getString("oname").split(",");
                    String[] otypes = json.getString("otype").split(",");
                    String[] otnames = json.getString("otname").split(",");
                    String[] purviews = json.getString("purview").split(",");

                    for (int j = 0; j < oids.length; j++) {
                        temp.getResource().put("rid", rid);
                        temp.getResource().put("rname", rname);
                        temp.getResource().put("rtype", rtype);
                        temp.getResource().put("oid", oids[j]);
                        temp.getResource().put("oname", onames[j]);
                        temp.getResource().put("otype", otypes[j]);
                        temp.getResource().put("otname", otnames[j]);

                        temp.getResource().put("uid", user.id());
                        temp.getResource().put("uname", user.iname());
                        temp.getResource().put("inherit", "0");

                        for (int k = 0; k < purviews.length; k++) {
                            temp.getResource().put("purview", purviews[k]);

                            if (!manager.containsPurview(rid, rtype, oids[j],
                                        otypes[j], Integer.parseInt(purviews[k]))) {
                            	temp.getResource().remove("pid");
                                util.manualSave1(temp, conn);
                            }
                        }
                    }
                }

                conn.commit();

                request.setAttribute("result", "{success: true}");
            } catch (Exception ex) {
                request.setAttribute("result", "{success: false, errCode: '-1'}");
                conn.rollback();
                ISystem.catchException(request, this, ex);
            } finally {
                SystemDataSource.closeConnection(conn);
            }
        } else {
            request.setAttribute("result", "{success: false, errCode: '-1'}");
        }

        return mapping.findForward("result");
    }

    /**
     * 获取可访问得文件及文件夹集合
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public ActionForward treeNodes(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);
        Map param = req.getResource();
        String folderid = StringTool.checkString(param.get("folderid"));
        String nodeid = StringTool.checkString(param.get("node"));
        // 如果文件夹号为空则从根目录开始，此处需要改进因为根目录编号不一定总是-1
        folderid = "".equals(folderid) ? "0" : folderid;

        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DmsSharedManager dsharedm = new DmsSharedManager(conn);

            List<TreeNode> nodeList = dsharedm.getChildrenFolder(user, nodeid);
            Recursion recursion = new Recursion();
            recursion.recursionFn2(nodeList, new TreeNode(nodeid, "0", "0"));
            request.setAttribute("result",
                recursion.modifyStr2(recursion.returnStr2.toString()));
            forward = mapping.findForward("result");
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
         * 获取可访问得文件及文件夹集合
         *
         * @param mapping
         * @param form
         * @param request
         * @param response
         * @throws Exception
         */
    public ActionForward list(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String start = StringTool.checkString(param.get("start"));

        String limit = StringTool.checkString(param.get("limit"));
        String pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    limit)) + 1);

        String folderid = StringTool.checkString(param.get("folderid"), "-1");

        request.setAttribute("folderid", folderid);

        StringBuffer where_file = new StringBuffer(" ");
        StringBuffer where_folder = new StringBuffer(" ");
        IUser user = ISystem.getSessionUser(request);

        if (!"".equals(folderid) && !"null".equals(folderid) &&
                (folderid != null)) {
            where_file.append(" AND doc_bvfabryjmq.COL_DIRECTORYID  = '" +
                folderid + "' ");
        }

        if (!"".equals(folderid) && !"null".equals(folderid) &&
                (folderid != null)) {
            where_folder.append(" AND doc_hgbgodkqxb.COL_PARENTFOLDERID  = '" +
                folderid + "' ");
        }

        String filePurviewSql = ObjectManager.getObjectPurviewSQL("FILEINFO",
                user, 0, ">=");

        String folderPurviewSql = ObjectManager.getObjectPurviewSQL("FOLDER",
                user, 0, ">=");

        String sql_file_2 = "SELECT doc_bvfabryjmq.PK_DOC_BVFABRYJMQ as id," +
            "doc_bvfabryjmq.COL_FILENAME as filename," +
            "doc_bvfabryjmq.COL_FILESIZE as filesize," +
            "isys_object.OBJ_CREATORNAME as creatorname," +
            "isys_object.OBJ_CREATETIME as createtime," +
            "isys_object.OBJ_UPDATETIME as updatetime," +
            "doc_bvfabryjmq.COL_VERSION as version," +
            "doc_bvfabryjmq.COL_STATE as state," +
            "doc_bvfabryjmq.COL_FILESUMMARY as summary," +
            "doc_bvfabryjmq.COL_FILETYPE as style," +
            "isys_object.OBJ_KEY as objkey," + "isys_object.ID as objid " +
            "FROM doc_bvfabryjmq Inner Join isys_object_relation ON doc_bvfabryjmq.PK_DOC_BVFABRYJMQ = isys_object_relation.OBJ_PKID " +
            "Inner Join isys_object ON isys_object_relation.ID = isys_object.ID " +
            "Inner Join (" + filePurviewSql +
            ") C ON isys_object.ID = C.OBJ_ID" + " WHERE " +
            "isys_object.OBJ_KEY = 'FILEINFO' " + where_file.toString() +
            " and OBJ_CREATORID <> '" + user.id() + "'";

        String sql_file_2_1 = "";

        DmsSharedManager dm = new DmsSharedManager();

        boolean canList = dm.InheritPurview(folderid, user);

        Map folderPurviewMap = dm.InheritPurviewMap(folderid, user);

        dm.clean();

        /*非根目录,需要判断目录的继承权限设置*/
        if (!folderid.equals("-1")) {
            /*如果继承该目录权限*/
            if (canList && !folderPurviewMap.containsKey("-1")) {
                String sqlHaving = "SELECT OBJ_ID FROM ISYS_PURVIEW WHERE OBJ_TYPE = 'FILEINFO' AND PURVIEW = -1 AND ROLE_ID = '" +
                    user.id() + "' AND ROLE_TYPE = 'user'";

                sql_file_2_1 = "SELECT doc_bvfabryjmq.PK_DOC_BVFABRYJMQ as id," +
                    "doc_bvfabryjmq.COL_FILENAME as filename," +
                    "doc_bvfabryjmq.COL_FILESIZE as filesize," +
                    "isys_object.OBJ_CREATORNAME as creatorname," +
                    "isys_object.OBJ_CREATETIME as createtime," +
                    "isys_object.OBJ_UPDATETIME as updatetime," +
                    "doc_bvfabryjmq.COL_VERSION as version," +
                    "doc_bvfabryjmq.COL_STATE as state," +
                    "doc_bvfabryjmq.COL_FILESUMMARY as summary," +
                    "doc_bvfabryjmq.COL_FILETYPE as style," +
                    "isys_object.OBJ_KEY as objkey," +
                    "isys_object.ID as objid " +
                    "FROM doc_bvfabryjmq Inner Join isys_object_relation ON doc_bvfabryjmq.PK_DOC_BVFABRYJMQ = isys_object_relation.OBJ_PKID " +
                    "Inner Join isys_object ON isys_object_relation.ID = isys_object.ID WHERE " +
                    "isys_object.OBJ_KEY = 'FILEINFO' " +
                    where_file.toString() + " and OBJ_CREATORID <> '" +
                    user.id() +
                    "' AND isys_object.ID not in (SELECT B.OBJ_ID FROM (" +
                    sqlHaving + ") B )";
            }
        }

        String sql_folder_2 = "SELECT doc_hgbgodkqxb.PK_DOC_HGBGODKQXB as id," +
            "doc_hgbgodkqxb.COL_FOLDERNAME as filename," +
            "doc_hgbgodkqxb.COL_FOLDERSIZE as filesize," +
            "isys_object.OBJ_CREATORNAME as creatorname," +
            "isys_object.OBJ_CREATETIME as createtime," + "'' as updatetime," +
            "'' as version," + "'' as state," +
            "doc_hgbgodkqxb.COL_FOLDERSUMMARY as summary," + "'' as style," +
            "isys_object.OBJ_KEY as objkey," + "isys_object.ID as objid " +
            " FROM isys_object_relation Inner Join isys_object ON isys_object_relation.ID = isys_object.ID " +
            "Inner Join doc_hgbgodkqxb ON doc_hgbgodkqxb.PK_DOC_HGBGODKQXB = isys_object_relation.OBJ_PKID " +
            "Inner Join (" + folderPurviewSql +
            ") C ON isys_object.ID = C.OBJ_ID " +
            "WHERE isys_object.OBJ_KEY =  'FOLDER' " + where_folder.toString() +
            " and OBJ_CREATORID <> '" + user.id() + "'";

        String sql_folder_2_1 = "";

        if (!folderid.equals("-1")) {
            if (canList && !folderPurviewMap.containsKey("-1")) {
                String sqlHaving = "SELECT OBJ_ID FROM ISYS_PURVIEW WHERE OBJ_TYPE = 'FILEINFO' AND PURVIEW = -1 AND ROLE_ID = '" +
                    user.id() + "' AND ROLE_TYPE = 'user'";

                sql_folder_2_1 = "SELECT doc_hgbgodkqxb.PK_DOC_HGBGODKQXB as id," +
                    "doc_hgbgodkqxb.COL_FOLDERNAME as filename," +
                    "doc_hgbgodkqxb.COL_FOLDERSIZE as filesize," +
                    "isys_object.OBJ_CREATORNAME as creatorname," +
                    "isys_object.OBJ_CREATETIME as createtime," +
                    "'' as updatetime," + "'' as version," + "'' as state," +
                    "doc_hgbgodkqxb.COL_FOLDERSUMMARY as summary," +
                    "'' as style," + "isys_object.OBJ_KEY as objkey," +
                    "isys_object.ID as objid " +
                    " FROM isys_object_relation Inner Join isys_object ON isys_object_relation.ID = isys_object.ID " +
                    "Inner Join doc_hgbgodkqxb ON doc_hgbgodkqxb.PK_DOC_HGBGODKQXB = isys_object_relation.OBJ_PKID " +
                    "WHERE isys_object.OBJ_KEY =  'FOLDER' " +
                    where_folder.toString() + " and OBJ_CREATORID <> '" +
                    user.id() +
                    "' AND isys_object.ID not in (SELECT B.OBJ_ID FROM (" +
                    sqlHaving + ") B )";
            }
        }

        String sql1 = "select count(id) from (" + sql_file_2 + " union " +
            ((!sql_file_2_1.equals("")) ? (sql_file_2_1 + " union ") : "") +
            sql_folder_2 +
            ((!sql_folder_2_1.equals("")) ? (" union " + sql_folder_2_1) : "") +
            ") as u";
        String sql2 = sql_file_2 + " union " +
            ((!sql_file_2_1.equals("")) ? (sql_file_2_1 + " union ") : "") +
            sql_folder_2 +
            ((!sql_folder_2_1.equals("")) ? (" union " + sql_folder_2_1) : "") +
            "  order by objkey desc,createtime";

        String url = request.getContextPath() + "/app/dms.do?method=list";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance()
                                             .createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, limit);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            Controller controller = plus.getController("form1");

            controller.setType("input");

            Label label = plus.getLabel();

            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            ListRange lr = new ListRange();
            lr.setTotalSize(label.totaldata());
            lr.setList(resultList);
            lr.setSuccess(true);

            request.setAttribute("result", JSONObject.fromObject(lr).toString());
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }
}
